<template>
  <div class="project-detail-view" v-loading="showLoading">
    <div v-if="!btnAuth.viewProjectDetailAuth">
      <no-auth></no-auth>
    </div>

    <template v-if="btnAuth && btnAuth.viewProjectDetailAuth">
      <!-- 顶部 S -->
      <div class="project-detail-view-title">
        <div class="project-detail-view-title-top">
          <div class="project-detail-view-title-top-left">
            <div class="project-name">{{ detailData.projectName }}</div>
            <div class="project-status" v-if="detailData.projectStatusName && detailData.projectStatusName.length" :style="{ backgroundColor: detailData.color || '#BDBDBD' }">{{ detailData.projectStatusName }}</div>
            <div class="project-progress">
              <el-progress :percentage="detailData.projectProcess"></el-progress>
            </div>
            <div class="cl_green progress-cursor" v-if="btnAuth.editProjectAuth" @click="handleClickProgress">{{ $t('common.projectManage.detail.progressManagement') }}</div>
          </div>
          <div class="project-detail-view-title-top-right">

            <!-- start 审批中icon -->
            <div class="approving-img" v-if="detailData.approveStatus === 1">
              <img :src="approvingImage" />
            </div>
            <!-- end 审批中icon -->
            <el-button type="primary" v-if="isShowProjectOpera" @click="clickDropDown(operateBtn[0].processId)">{{ operateBtn[0].buttonName }}</el-button>

            <el-dropdown trigger="click" v-if="isShowProjectOperaSelect" @command="clickDropDown">
              <el-button type="primary">
                {{ $t('common.projectManage.detail.projectOperations') }}
                <i class="iconfont icon-fdn-select"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="item in operateBtn" :key="item.id" :command="item.processId">
                  {{ item.buttonName }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <!-- 审批按钮 -->
            <template v-if="approveButtonData.length">
              <div v-for="(item, index) in approveButtonData" :key="item">
                <el-button class="ml_12" :key="index" type="primary" @click="openApproveDialog(item.enName)">{{ item.cnName }}</el-button>
              </div>
            </template>

            <!-- 撤回审批 -->
            <el-button v-if="allowoffApprove" class="ml_12" @click="offApproveAction">{{ $t('common.task.button.offApprove') }}</el-button>

            <!-- 已完成,已取消状态不显示该按钮 -->
            <el-button class="ml_12" v-if="isShowCancelBtn" @click="handleClickCancelProject">{{ $t('common.projectManage.detail.cancelProject') }}</el-button>

            <el-tooltip effect="dark" :content="$t('common.projectManage.detail.copyItem')" placement="bottom" v-if="btnAuth.createProjectAuth">
              <i class="iconfont icon-file-copy icon-btn" @click="copyProjectType"></i>
            </el-tooltip>

            <el-tooltip effect="dark" :content="$t('common.projectManage.detail.deleteItem')" placement="bottom" v-if="btnAuth.deleteProjectAuth">
              <i class="iconfont icon-delete icon-delete" @click="deleteProjectType"></i>
            </el-tooltip>

            <!-- 审批中的话 取消和编辑按钮隐藏 -->
            <template v-if="!detailData.approveStatus">
              <el-tooltip  effect="dark" :content="$t('common.projectManage.detail.editItem')" placement="bottom" v-if="btnAuth.editProjectAuth">
                <i class="iconfont icon-edit-square icon-edit" @click="editProjectType"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
        <ProjectTaskLabel :current-row-data="detailData"/>
      </div>
      <!-- 顶部 E -->

      <BaseTileLayoutTabBar
        v-if="taskLayout === 1"
        :bar-list="taskLayoutTabBarList"
        :now-item="leftActiveTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
      ></BaseTileLayoutTabBar>

      <base-collapse 
        class="project-detail-view-con" 
        :show-collapse="true" 
        :direction.sync="collapseDirection"
        :hidePartCollapse="hidePartCollapse" 
        :resize="true">
        <!-- 左边面板 -->
        <template slot="left">
          <div class="project-detail-view-con-left" v-show="collapseDirection != 'left'">
            <BaseTileLayoutTabBar 
              v-if="taskLayout === 2"
              :bar-list="leftTabList" 
              :now-item="leftActiveTab" 
              :structure="2" 
              @openLayoutModal="openBaseLayoutModal">
            </BaseTileLayoutTabBar>
            <div class="detail-con" v-if="leftActiveTab === 'project-detail'">
              <projectTypeFormView :fields="fields" :detailData="detailData" :form-cell-count="formCellCount" />
            </div>
          </div>
          <div class="extend-btn" v-show="collapseDirection == 'left'">{{ $t('common.projectManage.detail.projectDetails') }}</div>
        </template>

        <template slot="rightExtend">
          <div class="extend-btn" @click="rightActiveTab = 'project-detail-gantt'">
            {{ $t('common.projectManage.detail.tab.gantt') }}
          </div>
        </template>

        <!-- 右边面板 -->
        <template slot="right">
          <div class="project-detail-view-con-right" v-show="collapseDirection != 'right'">
            <BaseBarV3 
              v-if="taskLayout == 2"
              :bar-list="tabBarList" 
              :now-item="rightActiveTab" 
              @changeItem="tabBarChangeItem" 
              @upDateBarList="tabBarUpdateList">
            </BaseBarV3>
            <div class="content">
              <!-- 附加组件 -->
              <project-detail-card
                v-if="isAddOn(rightActiveTab)"
                ref="detailCard"
                :bizId="majorKeyId"
                :fromBizNo="detailData.projectNo"
                :card="currentCard"
              > 
              </project-detail-card>
              <!-- 客户评价 -->
              <div v-else-if="rightActiveTab === 'project-type-satisfaction'" class="messagebox-content">
                <iframe v-if="detailData.evaluated == 1" id="projectIframe" :src="iframeUrl" height="98%" width="100%"/>
                <no-data-view-new v-else :notice-msg="$t('im.detail.tips1')"></no-data-view-new>
              </div>

              <!-- 其他的组件 -->
              <component v-else :projectPlanTime="projectPlanTime" :is="rightActiveTab" :templateId="templateId" :projectId="majorKeyId" :btnAuth="btnAuth" :direction="collapseDirection" @updateProcess="updateProcess" :isPersonnelTab="isPersonnelTab" @jumpPersonTab="jumpPersonTab"></component>
            </div>
          </div>
        </template>
      </base-collapse>
    </template>

    <!-- 进度管理弹框 -->
    <progressManageDialog ref="progressManageRef" :projectId="majorKeyId" @progressSubmit="progressSubmit" />
  
    <!-- start 办理审批弹窗 -->
    <task-approve-dialog ref="approveDialogRef" :approve-id="approveId" :task-id="majorKeyId" moduleType="project" :projectApproveData="projectApproveData"/>
    <!-- end 办理审批弹窗 -->

    <!-- start 工单发起审批弹窗 -->
    <propose-approve-dialog ref="proposeApproveRef" moduleType="project" :task-id="majorKeyId" />
    <!-- end 工单发起审批弹窗 -->

    <!-- 通栏设置弹框 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="taskLayout"
      :columns="formCellCount"
      @changeLayout="changeTaskDetailLayout">>
    </biz-layout-modal>
  
  </div>
</template>
<script>
import { reactive, toRefs, onMounted, computed, nextTick, ref, watch } from 'vue';

import { MessageBox } from 'element-ui';
import { toast } from '@src/util/platform';
import platform from '@src/platform';
import i18n, { t } from '@src/locales';

import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum';
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi';
import { computedTabList } from '@src/util/tabBarUtils';
import { cloneDeep } from '@src/util/type';
import { useStateSystemViewLayout } from 'pub-bbx-utils'
import * as FormUtil from '@src/component/form/util'


import { 
  getProjectTypeField, 
  projectTypeDetail, 
  projectTypeCancel, 
  projectTypeRoleBtn, 
  projectTypePageDelete, 
  approveDetail, 
  projectStatusNextNode, 
  projectUpdateFlow, 
  approveCheck, 
  approveCancel,
  getAllCardList } from '@src/api/ProjectManage.ts';

import { fixDetail } from '@src/modules/projectManage/productTypeUtils/fixFields.js';
import { jumpProjectTypeEdit, jumpProjectTypeCopy, jumpPageProjectList, reloadTab } from '@src/modules/projectManage/productTypeUtils/jumpPage.js';

/** component */
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue';
import projectTypeFormView from '@src/modules/projectManage/components/projectTypeFormView.vue';
import projectTypeDynamicInfo from '@src/modules/projectManage/components/projectTypeDynamicInfo.vue';
import projectTypePersonManage from '@src/modules/projectManage/components/projectTypePersonManage.vue';
import projectTypeRoleManage from '@src/modules/projectManage/components/projectTypeRoleManage.vue';
import projectTypeWorkLog from '@src/modules/projectManage/components/projectTypeWorkLog.vue';
import projectTypeStatisticsBoard from '@src/modules/projectManage/components/projectTypeStatisticsBoard.vue';
import progressManageDialog from '@src/modules/projectManage/components/progressManageDialog.vue';
import projectDetailGantt from '@src/modules/projectManage/components/projectDetailGantt.vue';
import projectDetailCard from '@src/modules/projectManage/projectAddtionCard/projectDetailCard.vue';
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue';
import ProjectTaskLabel from '@src/modules/projectManage/components/projectTaskLabel.vue'
import NoDataViewNew from '@src/component/common/NoDataViewNew';

// 办理审批
import ApproveTaskDialog from '@src/modules/task/view/components/ApproveTaskDialog.vue';
// 发起审批
import ProposeApproveDialog from '@src/modules/task/view/components/ProposeApproveDialog.vue';

import noAuth from '@src/modules/calendar/noAuth.vue';
import projectTypeTaskList from '@src/modules/projectManage/components/projectTypeTaskList.vue';
import { migration } from '@src/component/form/util';
import { offApprove } from '@src/api/TaskApi.ts';

import { getLocalesOssUrl } from '@src/util/assets'
import { getRootWindow } from "@src/util/dom";
const approvingImage = getLocalesOssUrl('/task/approving.png')

export default {
  name: 'project-type-view',
  components: {
    BaseBarV3,
    projectTypeFormView,
    projectTypeDynamicInfo,
    projectTypePersonManage,
    projectTypeRoleManage,
    projectTypeWorkLog,
    projectTypeStatisticsBoard,
    progressManageDialog,
    projectDetailGantt,
    noAuth,
    projectTypeTaskList,
    projectDetailCard,
    [ApproveTaskDialog.name]: ApproveTaskDialog,
    [ProposeApproveDialog.name]: ProposeApproveDialog,
    BaseTileLayoutTabBar,
    ProjectTaskLabel,
    NoDataViewNew,
  },
  setup() {
    // 办理审批
    const progressManageRef = ref();
    // 发起审批
    const proposeApproveRef = ref();
    const projectDetailGanttRef = ref();
    const approveDialogRef = ref();
    const state = reactive({
      showLoading: false,
      fields: [],
      approvingImage,
      detailData: {
        projectName: '',
        projectStatusName: '',
        projectProcess: 0,
      },
      collapseDirection: '',
      rightActiveTab: '',
      tabBarList: [],
      operateBtn: [],
      // 按钮权限
      btnAuth: {
        createProjectAuth: false, // 新建
        deleteProjectAuth: false, // 删除
        editProjectAuth: false, // 编辑
        viewProjectDetailAuth: true, // 详情页面
        roleManageAuth: false, // 人员管理
        createTaskAuth: false, // 创建任务
      },
      currentCard: {},
      approveButtonData: [], // 审批按钮
      approveId: '', // 当前的审批id
      projectApproveData: {}, // 办理高级审批传参数数据
      leftTabList: [
        { 
          position: 'left',
          tabName: 'project-detail',
          disabled: true,
          tabLabel: t('common.projectManage.detail.projectDetails'),
          tabShow: true,
        },
      ],
      leftActiveTab: 'project-detail',
      formCellCount: 1,
      taskLayoutTabBarList: [],
      taskLayout: 2, // 布局方式 1:通栏 2:左右 
      tabPosition: '', // 记录tab位置  left|right
    });
    const iframeUrl = ref();

    // 通过关键字获取参数
    const getParamByUrl = key => {
      const url = new URL(location.href);
      return url.searchParams.get(key);
    };


    // 是否是附加组件
    const isAddOn = key => {
      let str = BaseTabBarUsualEnum.TabCardInfoSingle;
      return key.startsWith(str)
    };

    // 模板id
    const templateId = computed(() => {
      return getParamByUrl('templateId');
    });

    // 是否展示撤回审批按钮
    const allowoffApprove = computed(() => {
      // 是审批状态 是否是发起人 canRollBack可以撤回审批
      return state.detailData.approveStatus === 1 && state.projectApproveData?.data?.canRollBack
    })

    // 是否显示流转操作按钮 多个流转按钮
    const isShowProjectOperaSelect = computed(() => {
      return state.operateBtn?.length > 0 && state.operateBtn?.length != 1 && state.btnAuth.editProjectAuth && state.detailData?.projectStatusType != 'CANCEL' && state.detailData?.approveStatus !== 1;
    });
    // 单个流转按钮
    const isShowProjectOpera = computed(() => {
      return state.operateBtn?.length > 0 && state.operateBtn?.length == 1 && state.btnAuth.editProjectAuth && state.detailData?.projectStatusType != 'CANCEL' && state.detailData?.approveStatus !== 1;
    });

    // 取消按钮
    const isShowCancelBtn = computed(() => {
      return state.btnAuth.cancelProjectAuth && !(state.detailData?.projectStatusType === 'CANCEL' || state.detailData?.projectStatusType === 'COMPLETE') && state.detailData?.approveStatus !== 1;
    });
    // 项目id
    const majorKeyId = computed(() => {
      return getParamByUrl('id');
    });

    // 是否选中人员卡片
    const isPersonnelTab = computed(() => {
      return getParamByUrl('isPersonnelTab') || '';
    });

    const hidePartCollapse = computed(() => {
      if (state.taskLayout === 1) return state.tabPosition === 'left' ? 'right' : 'left';
      return '';
    })

    const projectPlanTime = computed(() => {
      return {
        proStart: state.detailData?.planStartTime ?? '',
        proEnd: state.detailData?.planEndTime ?? '',
      }
    })

    // 是否开启了满意度灰度
    const satisfactionGray = computed(() => {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.satisfaction || false;
    })

    // 获取表单字段
    const fetchFields = async () => {
      state.showLoading = true;
      try {
        let ret = await getProjectTypeField({
          templateId: templateId.value,
          tableName: 'project',
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.fields = [...(data || []), ...fixDetail];
      } catch (err) {
        console.log('error => fetchFields', err);
      }
    };

    // 获取详情数据
    const fetchDetail = async () => {
      state.showLoading = true;
      try {
        let ret = await projectTypeDetail({
          id: majorKeyId.value,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');
        // 处理富文本
        const newData = await FormUtil.initRichTextContent(state.fields, data)

        state.detailData = { ...newData, ...newData?.attribute };

        fetchOperationList();
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.showLoading = false;
      }
    };

    // 撤回审批
    const offApproveAction = async() => {
      const result = await MessageBox.confirm(i18n.t('task.tip.offApproveTip'));
      if (!result) return;

      approveCancel({ approveId: state.approveId, module: 'project' }).then(res => {
        if (res.status == 0) {
          state.approveButtonData = [] // 清除之前的审批按钮
          fetchDetail(); // 刷新页面
        } else {
          this.$platform.alert(res.message);
        }
      }).catch(err => {
      })
    };

    // 打开审批弹窗
    const openApproveDialog = type => {
      // type  同意/拒绝
      approveDialogRef.value.openDialog(type);
    }

    // 获取项目操作列表数据
    const fetchOperationList = async () => {
      try {
        let ret = await projectStatusNextNode({
          projectTypeId: templateId.value,
          name: state.detailData.projectStatusName,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.operateBtn = data;

        if (state.detailData.approveStatus) {
          // 在审批状态的话 请求审批按钮详情接口
          getApproveData()
        }
      } catch (err) {
        console.log('error => fetchOperationList', err);
      }
    };


    // 获取审批详情信息
    const getApproveData = async() => {
      try {
        let ret = await approveDetail({
          bizId: majorKeyId.value, // 项目id
          module: 'project',
          params: {
            processId: state.operateBtn[0].processId,
          }
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.projectApproveData = ret // 用于高级审批办理弹窗展示
        state.approveButtonData = data?.approveInfo?.buttons || []

        state.approveId = data?.approveId || ''
      } catch (err) {
        console.log('error => getApproveData', err);
      }
    }

    // 获取按钮权限
    const fetchProjectBtn = async () => {
      try {
        let ret = await projectTypeRoleBtn({
          projectId: majorKeyId.value,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.btnAuth = data;
      } catch (err) {
        console.log('error => fetchProjectBtn', err);
      }
    };

    const jumpPersonTab = () => {
      state.rightActiveTab = 'project-type-person-manage';      
    }
    /**
     * @des 初始化tabBar
     */
    const initRightTabBar = async () => {
      let { TabBarListItemKey: tabName, TabBarListItemLabel: tabLabel, TabBarListItemShow: tabShow, TabBarCardInfoType: tabIsCardType, TabCardInfoSingle: tabIsCardSingle, TabBarListItemType: tabType } = BaseTabBarUsualEnum;

      await initLayoutData()

      // 通栏模式tabPosition默认left
      if (state.taskLayout === 1) {
        state.tabPosition = 'left'
      }

      let cardInfoList = [];
      try {
        // 获取附加组件列表
        let { data, status, message } = await getAllCardList({projectTypeId: templateId.value});
        if(status !== 0){
          throw message
        }
        cardInfoList = data.map(item=>{
          const { id, cardName, fields} = item;
          return {
            ...item,
            config: item.bizConfig,
            fields: migration(fields || []),
            [tabName]: `${tabIsCardSingle}${id}`,
            [tabLabel]: cardName,
            [tabShow]:true,
            [tabType]:tabIsCardType
          }
        })
      } catch (error) {
        console.warn(error, 'error try catch getEnabledCardInfo');
      }

      let barArr = [
        { [tabName]: 'project-detail-gantt', disabled: true, [tabLabel]: i18n.t('common.projectManage.detail.tab.gantt'), [tabShow]: true },
        { [tabName]: 'project-type-dynamic-info', disabled: true, [tabLabel]: i18n.t('customer.detail.tabBar.dynamicInfo'), [tabShow]: true },
        { [tabName]: 'project-type-person-manage', disabled: false, [tabLabel]: i18n.t('common.projectManage.detail.tab.personnelManage'), [tabShow]: true },
        { [tabName]: 'project-type-role-manage', disabled: false, [tabLabel]: i18n.t('common.projectManage.detail.tab.roleManage'), [tabShow]: true },
        { [tabName]: 'project-type-work-log', [tabLabel]: i18n.t('common.projectManage.detail.tab.workLog'), [tabShow]: true },
        { [tabName]: 'project-type-statistics-board', [tabLabel]: i18n.t('common.projectManage.detail.tab.statisticsBoard'), [tabShow]: true },
        { [tabName]: 'project-type-task-list', [tabLabel]: i18n.t('common.projectManage.detail.tab.tab1'), [tabShow]: true },
        ...cardInfoList,
        { [tabName]: 'project-type-satisfaction', [tabLabel]: i18n.t('common.tabs.im.tabs3'), [tabShow]: satisfactionGray.value },
      ];

      barArr.forEach(tab => {
        tab.position = 'right'
      })

      let params_ = {
        equipment: StorageHttpParamsForTerminalType.PC,
        bizType: StorageHttpParamsForModuleType.ProjectType,
        bizTypeId: '0',
      };

      try {
        // 获取tabbar用户行为缓存
        let storageList = await getStorageForDetailTabbar(params_);
        if (storageList.status !== 0) {
          throw storageList.message;
        }
        let storageList_ = storageList.data.map(item => {
          const { cardId, checked } = item;
          return {
            [tabName]: cardId,
            [tabShow]: checked,
          };
        });
        
        barArr = computedTabList(barArr, storageList_);
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }

      state.tabBarList = barArr;

      nextTick(() => {
        let firstItem = barArr && barArr.find(item => item[tabShow]);
        state.rightActiveTab = isPersonnelTab.value ? 'project-type-person-manage' : firstItem?.[tabName];

        if (firstItem.tabType === 'is-cardinfo') {
          // 如果第一个是附加组件
          state.currentCard = firstItem
        }
      });
    };

    watch(
      ()=>[state.leftTabList, state.tabBarList], ([newValue1, newValue2]) => {
        state.taskLayoutTabBarList = cloneDeep([...newValue1, ...newValue2].filter(item => item.tabShow));
      },
      {
        deep: true
      }
    )

    // 切换tab
    const tabBarChangeItem = item => {
      let { TabBarListItemKey: tabName, TabBarListItemType: tabType, TabBarCardInfoType } = BaseTabBarUsualEnum;
      let { position } = item
      state.tabPosition = position

      // 通栏导航和左侧导航共用leftActiveTab数据
      if (state.taskLayout === 1 || position == 'left') {
        state.leftActiveTab = item[tabName];
      }
      // 右侧导航
      if (position == 'right') {
        state.rightActiveTab = item[tabName];
      }

      if (item[tabType] == TabBarCardInfoType) {
        state.currentCard = item
      }
    };

    /**
     * @des tabbar数据发生变更钩子函数
     */
    const tabBarUpdateList = list => {
      const { TabBarCardInfoType, TabBarListItemKey: tabName, TabBarListItemShow: tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item => {
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow],
        };
      });
      let params_ = {
        equipment: StorageHttpParamsForTerminalType.PC,
        bizType: StorageHttpParamsForModuleType.ProjectType,
        bizTypeId: '0',
        cardList: list_,
      };
      setStorageForDetailTabbar(params_);
    };

    // 取消项目
    const handleClickCancelProject = () => {
      MessageBox.confirm(i18n.t('common.projectManage.detail.cancelProjectTip'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            projectTypeCancel({ id: majorKeyId.value }).then(res => {
              instance.confirmButtonLoading = false;

              const { success, message, data } = res;
              if (!success) return toast(message, 'error');

              toast(i18n.t('common.base.tip.cancelSuccess'), 'success');

              done();
              fetchDetail();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // 删除
    const deleteProjectType = () => {
      MessageBox.confirm(i18n.t('common.projectManage.detail.deleteItemTip'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            projectTypePageDelete([majorKeyId.value]).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();

              reloadTab();
              jumpPageProjectList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // 新增和删除任务更新项目进度
    const updateProcess = () => {
      fetchDetail()
    };

    // 点击进度管理
    const handleClickProgress = () => {
      progressManageRef.value.openDialog();
    };

    // 编辑
    const editProjectType = () => {
      jumpProjectTypeEdit({ templateId: templateId.value, id: majorKeyId.value });
    };

    const copyProjectType = () => {
      jumpProjectTypeCopy({ templateId: templateId.value, id: majorKeyId.value });
    };

    const clickDropDown = async processId => {

      // 判断是否需要高级审批
      const approveParams = {
        bizId: majorKeyId.value,
        module: 'project',
        params: {
          processId: processId,
        }
      }

      let res = await approveCheck(approveParams);
      if (!res.success) return toast(res.message, 'error');
      if (res.data?.needApprove) {
        // 需要高级审批
        // 发起审批
        proposeApproveRef.value.openDialog(res.data);
      } else {
        try {
          const params = {
            projectId: majorKeyId.value,
            projectTypeId: templateId.value,
            processId: processId,
          };

          let res = await projectUpdateFlow(params);

          if (!res.success) return toast(res.message, 'error');

          toast(i18n.t('common.base.tip.updateSuccess'), 'success');

          fetchDetail();
        } catch (error) {
          console.warn(error, 'error try catch clickDropDown');
        }
      }
    };

    // 进度更新成功
    const progressSubmit = () => {
      fetchDetail();
    };

    /** 通栏 S */
    const bizLayoutModal = ref(null)

    const openBaseLayoutModal = ()=>{
      bizLayoutModal.value.open()
    }
    const changeTaskDetailLayout = (type, columns)=>{
      state.formCellCount = columns * 1;
      state.taskLayout = type;
      state.leftActiveTab = state.leftTabList[0]?.tabName;
      state.tabPosition = 'left';
      if (type === 2) {
        state.rightActiveTab = state.tabBarList[0].tabName
      }
    }

    async function initLayoutData(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      state.taskLayout = count.baseLayout || 2;
      state.formCellCount = count.formCellCount || 1;
    }

    async function getConversationInit() {
      const id = majorKeyId.value;
      iframeUrl.value = `/pcoperation/task/evaluate?id=${id}&fromProject=true`;
    }

    onMounted(async () => {
      if (window.frameElement) {
        // 初始化title
        let currTabId = window.frameElement.dataset.id;
        platform.setTabTitle({
          id: currTabId,
          title: i18n.t('common.projectManage.detail.projectDetails')
        })
      }
      initRightTabBar();
      await fetchFields();
      fetchDetail();
      fetchProjectBtn();
      getConversationInit();
    });

    return {
      satisfactionGray,
      iframeUrl,
      projectPlanTime,
      progressManageRef,
      proposeApproveRef,
      approveDialogRef,
      ...toRefs(state),
      tabBarChangeItem,
      tabBarUpdateList,
      templateId,
      majorKeyId,
      handleClickCancelProject,
      deleteProjectType,
      updateProcess,
      handleClickProgress,
      editProjectType,
      copyProjectType,
      clickDropDown,
      progressSubmit,
      isShowProjectOperaSelect,
      isShowProjectOpera,
      isShowCancelBtn,
      isAddOn,
      offApproveAction,
      allowoffApprove,
      openApproveDialog,
      isPersonnelTab,
      jumpPersonTab,
      bizLayoutModal,
      openBaseLayoutModal,
      changeTaskDetailLayout,
      hidePartCollapse
    };
  },
};
</script>
<style lang="scss" scoped>
@import '@src/modules/projectManage/projectTypeView/detail.scss';
::v-deep .el-button {
      border-radius: 4px;
  }
  .approving-img {
    margin-top: 10px;
    img {
      width: 80px;
    }
  }
.messagebox-content {
  height: 100%;
  overflow-y: auto;
}
</style>